﻿

//

using Microsoft.AspNetCore.Components;
using LaserMark.Components.Services;
using LaserMark.Control.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LaserMark.Components;
public partial class HeaderStatus
{
    [Inject]
    [NotNull]
    private IGlobalStatus? GlobalStatus { get; set; }
    [NotNull]
    private bool IsRunning { get; set; }
    [NotNull]
    private bool IsStop { get; set; }

    [Inject]
    [NotNull]
    private IControl? Control { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            _ = Task.Run(async () =>
            {
                while (true)
                {
                    if (GlobalStatus.IsRunning)
                    {
                        int value;
                        await Control.GetDi(0, mc.MC_GPI, out value);
                        var status = Convert.ToString(value, 2).PadLeft(16, '0');
                        if (status[13] == '1')
                        {
                            IsRunning = false;
                            if (!IsStop)
                            {
                                IsStop = true;
                            }
                        }
                        else
                            IsStop = false;
                        if (!IsRunning)
                            IsRunning = true;

                        if (IsStop)
                        {
                            await InvokeAsync(StateHasChanged);
                        }
                        if (IsRunning)
                        {
                            await InvokeAsync(StateHasChanged);
                        }
                        await Task.Delay(500);
                    }
                }
            });
        }
    }
}
